package com.ruoyi.network.message;


import com.ruoyi.common.utils.HexUtil;
import com.ruoyi.exception.CommandNotRightException;
import com.ruoyi.network.CommandType;

/**
 * 处理接收到的消息
 */
public class ReceivedMessage {

    /**
     * 完整的十六进制消息
     */
    private String full;

    /**
     * 包头
     */
    private String frameHeader;

    /**
     * 设备编号
     */
    private String deviceCode;

    private String version;

    /**
     * 数据长度，10进制
     */
    private int dataLength;

    /**
     * 命令，十六进制
     */
    private String cmd;

    /**
     * 十六进制数据部分
     */
    private String dataHex;

    public ReceivedMessage(String hex) throws CommandNotRightException {

        this.full = hex;

        this.analysisCommand();
    }

    private void analysisCommand() throws CommandNotRightException {

        if(this.full.length()%2==1){

            throw new CommandNotRightException();
        }

        this.frameHeader = this.full.substring(0, 2);
        if(this.frameHeader.equalsIgnoreCase("55")==false){

            throw new CommandNotRightException();
        }

        //3737373737373737
        this.deviceCode = this.full.substring(2, 18);
        byte[] data = HexUtil.hexStringToByteArray(deviceCode);
        this.deviceCode = new String(data);

        this.version = this.full.substring(18, 20);

        String length = this.full.substring(20, 22);
        this.dataLength = Integer.parseInt(length, 16);

        this.cmd = this.full.substring(22, 24);

        this.dataHex = this.full.substring(24, this.full.length()-4);

        if(this.dataHex.length() != this.dataLength * 2){
            throw new CommandNotRightException();
        }

        //获取crc校验
        String crc = this.full.substring(this.full.length()-4);

        //上位机要对传递过来的数据计算crc值
        byte[] crcBytes = HexUtil.hexStringToByteArray(this.full.substring(0, this.full.length()-4));
        String crc2 = HexUtil.getCRC(crcBytes);

        //计算出来的值和传递过来的值比较
        if(!crc2.substring(2,4).equalsIgnoreCase(crc.substring(0, 2)) || !crc2.substring(0,2).equalsIgnoreCase(crc.substring(2, 4))){
            throw new CommandNotRightException();
        }

    }

    public String getFull() {
        return full;
    }

    public String getFrameHeader() {
        return frameHeader;
    }

    public String getDeviceCode() {
        return deviceCode;
    }

    public String getVersion() {
        return version;
    }

    public int getDataLength() {
        return dataLength;
    }

    public String getCmd() {
        return cmd;
    }

    public CommandType getCmdType(){
        int value = Integer.parseInt(cmd, 16);
        return CommandType.valueOf(value);
    }

    public String getDataHex() {
        return dataHex;
    }
}
